import request from '@/utils/request'
export function listMenu(query) {
  return request({
    url: '/system/menu/list',
    method: 'get',
    params: query
  })
}

/**
 * 后台查询数据返回是全查的数据
 * 递归构造树型结构数据
 */
export function handleTree(data, id, parentId, children) {//data为传入的所有数据，id为menuId
	//初始化
	let config = {
		id: id || 'id',
		parentId: parentId || 'parentId',
		childrenList: children || 'children'
	};

	var childrenListMap = {};//用于存放子级节点
	var nodeIds = {};//用于访问当前节点
	var tree = [];//产生树

	for (let d of data) {
		//获取根节点
		let parentId = d[config.parentId];
		//初始化下级节点
		if (childrenListMap[parentId] == null) {
			childrenListMap[parentId] = [];
		}
		//config.id = menuId d[menuId]= 1 nodeIds[1] = 赋值第一条数据
		nodeIds[d[config.id]] = d;
		//添加下级节点
		childrenListMap[parentId].push(d);
	}
	//添加树节点
	for (let d of data) {
		let parentId = d[config.parentId];
		if (nodeIds[parentId] == null) {
			tree.push(d);
		}
	}
	//添加子级节点
	for (let t of tree) {
		adaptToChildrenList(t);
	}

	//递归添加子级节点
	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.id]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.id]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}

	return tree;
}

// 新增菜单
export function addMenu(data) {
  return request({
    url: '/system/menu/add',
    method: 'post',
    data: data
  })
}

// 修改菜单
export function updateMenu(data) {
  return request({
    url: '/system/menu/update',
    method: 'put',
    data: data
  })
}

// 删除菜单
export function delMenu(menuId) {
  return request({
    url: '/system/menu/' + menuId,
    method: 'delete'
  })
}

// 查询菜单详细
export function getMenu(menuId) {
  return request({
    url: '/system/menu/' + menuId,
    method: 'get'
  })
}

// 全查询角色的菜单下拉列表
export function roleMenuTreeSelect() {
  return request({
    url: '/system/menu/roleMenuTreeSelect',
    method: 'get'
  })
}

// 根据角色ID查询菜单下拉树结构
export function roleMenuTreeSelectById(roleId) {
  return request({
    url: '/system/menu/roleMenuTreeSelect',
    method: 'get',
    params: roleId
  })
}

// 查询菜单下拉树结构
export function treeSelect() {
  return request({
    url: '/system/menu/treeSelect',
    method: 'get'
  })
}
